/**
 * Package:com.goldcity.codec.encoder;
 * $Id: BinaryEncoder.java,v 1.1 2009/03/20 08:34:35 yangc Exp $
 * Copyright(c) 2001-2005 www.afteryuan.com
 */
package com.afteryuan.server.mina.codec;

import org.apache.mina.filter.codec.ProtocolEncoderOutput;
import org.apache.mina.filter.codec.ProtocolEncoderAdapter;
import org.apache.mina.core.session.IoSession;
import org.apache.mina.core.buffer.IoBuffer;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.afteryuan.server.command.down.core.PolicyDown;
import flex.messaging.io.SerializationContext;
import flex.messaging.io.amf.Amf3Output;

import java.io.ByteArrayOutputStream;


/**
 * BinaryEncoder类 下行命令编码器
 * <p/>
 * <p><a href="BinaryEncoder.java.html"><i>View Source</i></a></p>
 *
 * @author <a href="mailto:afteryuan@afteryuan.com">$Author: yangc $</a>
 * @version $Revision: 1.1 $
 */
public class Amf3Encoder extends ProtocolEncoderAdapter {
    private static Log log = LogFactory.getLog(Amf3Encoder.class);
    /**
     * 编码方法，如果是String则看是不是安全策略文件，是则直接write
     * 否则进行amf3编码，压缩，发送
     * @param o 需要编码的对象
     * @param out 输出对象
     * @throws Exception
     */
    public void encode(IoSession ioSession, Object o, ProtocolEncoderOutput out) throws Exception {
        if(o instanceof PolicyDown){
            PolicyDown policyDown = (PolicyDown) o;
                IoBuffer ioBuffer = IoBuffer.allocate(policyDown.getPolicy().length()).setAutoExpand(true);
                ioBuffer.put(policyDown.getPolicy().getBytes());
                ioBuffer.flip();
                out.write(ioBuffer);
                return;
        }
        Amf3Output amfOut = new Amf3Output(SerializationContext.getSerializationContext());
        ByteArrayOutputStream outStream = new ByteArrayOutputStream();
        amfOut.setOutputStream(outStream);
        amfOut.writeObject(o);

        byte[] obyte = outStream.toByteArray();
        IoBuffer ioBuffer = IoBuffer.allocate(obyte.length).setAutoExpand(true);
        ioBuffer.put(obyte);
        ioBuffer.flip();
        out.write(ioBuffer);

    }

    /**
     * 销毁编码器对象
     * @param ioSession socket连接会话
     * @throws Exception
     */
    public void dispose(IoSession ioSession) throws Exception {

    }
}